var assert = require("assert");
var fs = require('fs');

var _ = require("lodash");
var unirest = require('unirest');
var Random = require("random-js");
var async = require("async");
var typeCheck = require('type-check').typeCheck;

var QQ = require("./model.js").QQ;
var cookieJar = unirest.jar();


/**
 * 用户登录状态
 */
var LoginStatus = function() {
	this.status = 0;
};

LoginStatus.statusDesc = {
	0: "未登录"
};


var WebQQWorker = function(qqNumber) {
	this.qq = new QQ(qqNumber);
	this.login();

	this.loginStatus = 0;
}


WebQQWorker.prototype.login = function() {
	var that = this;

	var clientId = Random.integer(111111, 888888);
	var referer = "http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2";
	var smartQQUrl = "http://w.qq.com/login.html";

	var cookies = {};

	async.waterfall([
		// 访问 webqq 首页，抓取登录 url
		function(callback) {
			unirest.get(smartQQUrl).end(function(res) {
				var loginUrlRegex = /\.src\ =\ "(.+?)"/;

				_.extend(cookies, res.cookies);

				try {
					var loginUrl = res.body.match(loginUrlRegex)[1];

				} catch(e) {
					console.error(e);
					var loginUrl = "";
				}

				callback(null, loginUrl);
			});
		},
		// 访问登录页面 获取二维码地址以及页面中的一些必要信息
		function(loginUrl, callback) {
			assert(!_.isEmpty(loginUrl));

			unirest.get(loginUrl).end(function(res) {
				var webQQInfo = {};
				_.extend(cookies, res.cookies);

				var loginPageHtml = res.body;
				assert(!_.isEmpty(loginPageHtml));

				var appidRegex = /g_appid=encodeURIComponent\(\"(\d+)\"\)/;
				var signRegex = /g_login_sig=encodeURIComponent\(\"(.*?)\"\)/;
				var jsVerRegex = /g_pt_version=encodeURIComponent\(\"(\d+)\"\)/;
				var miBaoCssRegex = /g_mibao_css=encodeURIComponent\(\"(.*?)\"\)/;

				try {
					var appid = loginPageHtml.match(appidRegex)[1];
					var sign = loginPageHtml.match(signRegex)[1];
					var jsVer = loginPageHtml.match(jsVerRegex)[1];
					var miBaoCss = loginPageHtml.match(miBaoCssRegex)[1];

					webQQInfo = {
						appid: appid,
						sign: sign,
						jsVer: jsVer,
						miBaoCss: miBaoCss,
						loginUrl: loginUrl
					}

				} catch(e) {
					console.dir(e);
					webQQInfo = {};
				}

				callback(null, webQQInfo);
			});
		},
		// 获取二维码图片，获取并保存页面中的 cookies
		function(webQQInfo, callback) {
			assert(!_.isEmpty(webQQInfo));

			var appId = webQQInfo.appid;
			var qrCodeUrl = `https://ssl.ptlogin2.qq.com/ptqrshow?appid=${appId}&e=0&l=L&s=8&d=72&v=4`;
			var getQrCodeAt = (new Date()).getTime();

			/*pt_login_sig=Yf4jU29Q1MAYPS21d1hGV-Lwu5MNNr2YnuWcWYjG9mTMQy7Gc9tJzaUzekrpjwlr; pt_clientip=74447f000001fd95; pt_serverip=b4140aa693da103d; uikey=cda4bd0521d35bacacfa1bc10f6c07851a447846b6ea2a39fed983af37eda8bb*/

			var cookiesArray = [];
			_.forEach(cookies, function(v, k) {
				if (_.indexOf(["pt_login_sig", "pt_clientip", "pt_serverip", "uikey"], k) === -1) {
					return true;

				} else {
					cookiesArray.push(`${k}=${v}`);
				}
			});
			var cookiesStr = cookiesArray.join("; ");

			unirest.get(qrCodeUrl).encoding("binary").headers({
				"header": cookiesStr

			}).end(function(res) {
				_.extend(cookies, res.cookies);

				res.setEncoding("binary");
				fs.writeFile(`./qrcode/${that.qq.number}.png`, res.body, {encoding: "binary"}, function(err) {
					if (err) {
						return callback(err);
					}

					console.log(`qq: ${that.qq.number}'s qrcode save success`);
					callback(null, webQQInfo, getQrCodeAt);
				});
			});
		},
		// 轮询确认用户是否已经成功扫描
		function(webQQInfo, getQrCodeAt, callback) {
			// assert(!_.isEmpty(webQQInfo));
			// assert(!_.isEmpty(getQrCodeAt));

			var timeDelta = (new Date()).getTime() - getQrCodeAt;
			var url = `https://ssl.ptlogin2.qq.com/ptqrlogin?webqq_type=10&remember_uin=1&login2qq=1&aid=${webQQInfo.appid}&u1=http%3A%2F%2Fw.qq.com%2Fproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=0-0-${timeDelta}&mibao_css=${webQQInfo.miBaoCss}&t=undefined&g=1&js_type=0&js_ver=${webQQInfo.jsVer}&login_sig=${webQQInfo.sign}`;

			var cookiesArray = [];
			_.forEach(cookies, function(v, k) {
				if (_.indexOf(["pt_login_sig", "pt_clientip", "pt_serverip", "uikey", "qrsig"], k) === -1) {
					return true;

				} else {
					console.dir(v)
					cookiesArray.push(`${k}=${v}`);
				}
			});
			var cookiesStr = cookiesArray.join("; ");

			// 轮询登录状态
			setInterval(function() {
				unirest.get(url).header({
					"Cookie": cookiesStr,

				}).end(function(res) {
					var ret = res.body.split("'");

					switch(ret[1]) {
						case "65":
							// 尝试重新登录
							return callback("qrcode 失效");
							break;
						case "0":
							_.extend(cookies, res.cookies);

			_.forEach(cookies, function(v, k) {
				if (_.indexOf(["pt_login_sig", "pt_clientip", "pt_serverip", "uikey", "qrsig"], k) === -1) {
					return true;

				} else {
					console.dir(v)
					cookiesArray.push(`${k}=${v}`);
				}
			});
			var cookiesStr = cookiesArray.join("; ");

							unirest.get(ret[5]).header({
								"Cookie": cookiesStr
							}).end(function(res) {
								console.dir(res.body);
								callback(null);
							});
							break;
						case "66":
							console.info("未失效，等待用户验证");
							break;
						case "67":
							console.info("验证中");
							break;
						default:
							console.error(res.body);
							callback("未知错误");
					}
				});
			}, 1000);
		}
	],
	function(err, ress) {
		if (err) {
			console.error(err);
		}

	});
};


exports.WebQQWorker = WebQQWorker;
